package cn.stylefeng.guns.core.pojo.page;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.ReflectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Data;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

@Data
public class AndaPageResult<T>  implements Serializable {

    private Boolean asc;

    private String column;

    private int current;

    private List<T> list;

    private List<OrderItem> orders = new ArrayList<>();

    private int pages;

    private Boolean searchCount;

    private int size;

    private Object summary;

    private int total;




    private static final long serialVersionUID = -1L;

    /**
     * 默认分页彩虹展示数量
     */
    public static final int RAINBOW_NUM = 5;


    public  AndaPageResult<T>  AndaPageResult(Page page,T object) {
        Object asc = null;
        Object column = null;
        Object orders = null;
        try {
             asc = ReflectUtil.getFieldValue(object, "asc");
             column = ReflectUtil.getFieldValue(object, "column");
             orders = ReflectUtil.getFieldValue(object, "orders");
        } catch (Exception e) {
            e.printStackTrace();
        }
        OrderItem orderItem =null;
        if(asc!=null){
            orderItem =  new OrderItem(column == null ? null : column.toString(), Boolean.valueOf(asc.toString()));
            this.setAsc(Boolean.valueOf(asc.toString()));
        }else {
            orderItem =  new OrderItem(column == null ? null : column.toString(), false);
            this.setAsc(false);
        }
        List<OrderItem> orderItems = JSON.parseArray(orders.toString(), OrderItem.class);
        orderItems.add(orderItem);

        this.setColumn(column==null?null:column.toString());
        this.setOrders(orderItems);
        this.setCurrent(Convert.toInt(page.getCurrent()));
        this.setList(page.getRecords());
        this.setPages(PageUtil.totalPage(Convert.toInt(page.getTotal()),
                Convert.toInt(page.getSize())));
        this.setSearchCount(true);
        this.setSize(Convert.toInt(page.getSize()));
        this.setTotal(Convert.toInt(page.getTotal()));

        return this;
    }




    public static<T> Object getFieldValue(T obj,String filedName){
        Class<?> clazz = obj.getClass();
        while (clazz != null) {
            try {
                Field field = clazz.getDeclaredField(filedName);
                field.setAccessible(true);
                return field.get(obj);
            } catch (NoSuchFieldException e) {
                // 字段不存在于当前类，继续查找父类
                clazz = clazz.getSuperclass();

            } catch (IllegalAccessException e) {
                e.printStackTrace();
                return null;
            }
        }
        // 字段未找到
        return null;
    }



}
